package nl.gamayun.whohasit.services;

import nl.gamayun.whohasit.Loan;
import nl.gamayun.whohasit.R;
import nl.gamayun.whohasit.WhoHasItActivity;
import nl.gamayun.whohasit.utils.WhoHasItUtils;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;

public class NotifyService extends IntentService {

	static final String TAG = NotifyService.class.getSimpleName();
	
	private NotificationManager notificationManager; 
	private Notification notification;
	
	
	public NotifyService() {
		super(TAG);
		Log.d(TAG, "UpdaterService constructed");
	}
	
	@Override
	protected void onHandleIntent(Intent inIntent) 
	{
		Log.d(TAG, "onHandleIntent");
		this.notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		this.notification = new Notification(android.R.drawable.stat_notify_chat,"", 0);
		long loanId = inIntent.getLongExtra(WhoHasItService.TO_LATE_LOAN, -1);
		if (loanId > 0)
		{
			Loan loan = WhoHasItUtils.getWhoHasItHandler(this).getLoan(loanId);
			if (loan != null)
				sendToLateNotification(loan);
		}
	}
	
	private void sendToLateNotification(Loan loan) 
	{
		Log.d(TAG, "sendToLateNotification");
		PendingIntent pendingIntent = PendingIntent.getActivity(this, -1, new Intent(this, WhoHasItActivity.class),
		PendingIntent.FLAG_UPDATE_CURRENT); 
		this.notification.when = System.currentTimeMillis(); 
		this.notification.flags |= Notification.FLAG_AUTO_CANCEL; 
		CharSequence notificationTitle = this.getText(R.string.notification_to_late_title); 
		CharSequence notificationSummary = this.getString(R.string.notification_to_late_message, loan.getDetailFull());
		this.notification.setLatestEventInfo(this, notificationTitle, notificationSummary, pendingIntent); 
		this.notificationManager.notify(0, this.notification);
	}

}
